#!/bin/bash
# if good then we can go for native speed.
# is it?
hwd=$PWD
function find_target {
	cd metalazero/remote_control/discovery
	# timeout this shit?
	#timeout 5 python3 broadcast_server.py --unique 1 &> ~/.kali_uuid &
	# will close the server after the whole thing right?
	rm ~/.kali_uuid
	bash ~/kali_connect.sh < ~/kali_execute_remote.sh | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | xargs -iabc python3 uuid_client.py -i abc >> ~/.kali_uuid
	#bash ~/kali_connect.sh < ~/kali_execute_remote.sh | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | xargs -iabc python3 broadcast_client.py -i abc
	# are you sure? when to check the shit?
	#sleep 5
	sed -i "s/'/\"/g" ~/.kali_uuid
	# check the file.
	#echo checking ~/.kali_uuid
	#cat ~/.kali_uuid
	python3 get_fastest_ip.py -f $HOME/.kali_uuid -u '6a752697-0f8c-4100-9405-b9abc24e84a8' > ~/.kali_ip
	#cat ~/.kali_ip | xargs -iabc -o  bash ~/kali_native_connect.sh abc
	cd $hwd
}
function connect_kali {
	cat ~/.kali_ip | head --lines 1 | xargs -iabc -o bash -c "bash ~/kali_native_connect.sh abc || exit 0"
	#exit
}
# this is not the ultimate verification.
function safe_connect  {
	target=`cat ~/.kali_ip | head --lines 1 | xargs -iabc ping -w 1 abc | grep -Eo "100% packet loss"`
	if [ "$target" == "100% packet loss" ]; then
		# must rebuild the shit.
		echo there is no way to connect to the server.
	else
		connect_kali
		exit
	fi
}
rm ~/.kali_lock
# check the thing first.
if [[ ! -f .kali_ip ]]; then
	find_target
	safe_connect
fi

#cat .kali_ip | head --lines 1 | xargs -iabc -o bash -c "bash kali_native_connect.sh abc || exit 0"
t=$(cat ~/.kali_ip | wc -c)
#echo $t
if [[ -f .kali_ip ]] || [ $t -lt 2 ]; then 
	find_target
	safe_connect
	# get that running in the background?
#if [ $? -ne 0 ] || [ $t -lt 2 ]; then 
fi
